package ase.assignment.sts.db.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import ase.assignment.sts.api.CustomerHandler;
import ase.assignment.sts.beans.CustomerEntity;
import ase.assignment.sts.db.DBHandler;

/**
 * @author Lionel
 * 
 */
public class CustomerHandlerImpl implements CustomerHandler {
	CustomerHandlerImpl() {

	}

	public void create(CustomerEntity customer) {
		String sql = "insert into Customers values('" + customer.getName()
				+ "','" + customer.getPassword() + "','" + customer.getEmail()
				+ "')";
		try {
			System.out.println(sql);
			DBHandler.getInstance().createStatement().executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBHandler.getInstance().dispose();
		}
	}

	public boolean login(String username, String password) {
		if (username == null || password == null) {
			return false;
		}
		boolean isOk = false;
		String sql = "select password from Customers where name = '" + username
				+ "' and password='" + password.trim() + "'";
		try {
			System.out.println(sql);
			ResultSet rs = DBHandler.getInstance().createStatement()
					.executeQuery(sql);
			isOk = rs != null && rs.next();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBHandler.getInstance().dispose();
		}
		return isOk;
	}

	public void logout(String username) {
		// TODO no db access
	}

	public void update(CustomerEntity customer) {
		String sql = "update Customers set password='" + customer.getPassword()
				+ "', email='" + customer.getEmail() + "' where name = '"
				+ customer.getName() + "'";
		try {
			System.out.println(sql);
			DBHandler.getInstance().createStatement().executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBHandler.getInstance().dispose();
		}
	}

	public void close(String username) {
		String sql = "delete from Customers where name = '" + username + "'";
		try {
			System.out.println(sql);
			DBHandler.getInstance().createStatement().executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBHandler.getInstance().dispose();
		}
	}

	public CustomerEntity find(String username) {
		String sql = "select password, email from Customers where name='"
				+ username + "'";
		try {
			System.out.println(sql);
			ResultSet rs = DBHandler.getInstance().createStatement()
					.executeQuery(sql);
			if (rs != null && rs.next()) {
				CustomerEntity entity = new CustomerEntity(username);
				entity.setPassword(rs.getString(1).trim());
				entity.setEmail(rs.getString(2).trim());
				return entity;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBHandler.getInstance().dispose();
		}
		return null;
	}

}
